//
//  MyViewController.m
//  shise
//
//  Created by 徐国庆 on 14/12/17.
//  Copyright (c) 2014年 apple. All rights reserved.
//

#import "MyViewController.h"
#import "MyselfDetailViewController.h"// “个人信息”视图控制器
#import "MyCollectViewController.h"// “我的收藏”视图控制器
#import "VersionInformationViewController.h"// ”版本信息“视图控制器
#import "UIImageView+WebCache.h"
#import "DataBaseHaneler.h"
#import "Food.h"
//#import <ShareSDK/ShareSDK.h>
#import <MessageUI/MessageUI.h>
#import "UIImageView+WebCache.h"
#import "SDImageCache.h"
#import "WBSDKBasicButton.h"
#import "WeiboSDK.h"
#import "WBSDKRelationshipButton.h"
#import "NetHandler.h"
#import "WeiboLog.h"
#import "AppDelegate.h"
#import "WeiboSDK.h"
#import "MineCellTableViewCell.h"
@interface MyViewController ()<UITableViewDataSource, UITableViewDelegate, MFMailComposeViewControllerDelegate,UIAlertViewDelegate, WBHttpRequestDelegate>

// 定义数组装“我的收藏”“清除缓存”“版本信息”内容
@property(nonatomic,retain)NSMutableArray *array;

@property(nonatomic,retain)UIAlertView *alertView;
@property(nonatomic,retain)UIAlertView *alertViewAdvice;
@property(nonatomic,retain)NSMutableArray *arrayImage;//装图片的数组
@property(nonatomic,retain)UIButton *buttonlogin;

@property(nonatomic,retain)UIImageView *photoHead;//用户头像
@property(nonatomic,retain)UILabel *nameLabel;//微博名字
@property(nonatomic,retain)UILabel *fansLabel;//粉丝数
@property(nonatomic,retain)UILabel *seeLabel;//关注的人数
@property(nonatomic,retain)UILabel *weiboLabel;//发过的微博数
@property(nonatomic,retain)UIButton *login;//登录按钮
@property(nonatomic,retain)UIImageView *weiboPhoto;//用户登录的自己的头像

@property(nonatomic,retain)WeiboLog *weiboObject;//微博作为对象


@end


@implementation MyViewController

- (void)dealloc
{
    [_array release];
    [_alertView release];
    [_alertViewAdvice release];
    [_buttonlogin release];
    [_arrayImage release];
    [_photoHead release];
    [_nameLabel release];
    [_fansLabel release];
    [_seeLabel release];
    [_weiboLabel release];
    [_login release];
    [super dealloc];
}

// 初始化数组
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self= [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        
        
        // 通知中心
        
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        [center addObserver:self selector:@selector(receiveNotifica:) name:@"suibian" object:@"随便"];
        
        
//        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
//        [center addObserver:self selector:@selector(receiveNotification:) name:@"login" object:nil];
//
        
        //放在cell上得图片数组
        self.arrayImage = [NSMutableArray arrayWithObjects:@"iconfont-tiantianquanor.png",@"iconfont-regouor.png",@"iconfont-xingguangor.png",@"iconfont-lengyinor.png",@"iconfont-tanghuluor.png" ,nil];
        //每个cell上面的内容
        self.array = [NSMutableArray arrayWithObjects:@"我的收藏", @"清除收藏", @"清除缓存", @"相关信息", @"意见反馈", nil];
    }
    return self;
}




- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"注销" style:UIBarButtonItemStylePlain target:self action:@selector(zhuxiao:)];
    self.navigationItem.rightBarButtonItem = nil;
    //背景图片
    
    UIImageView *headImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.navigationController.navigationBar.frame.size.height, self.view.frame.size.width, self.view.frame.size.height/6*3)];
    //    headImageView.backgroundColor = [UIColor redColor];
    headImageView.userInteractionEnabled = YES;
    headImageView.image = [UIImage imageNamed:@"zanshide.jpg"];
    [self.view addSubview:headImageView];
    [headImageView release];
    
    
    // 设置头像
    self.photoHead = [[UIImageView alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2, self.view.frame.size.height/6, 80, 80)];
    self.photoHead.image = [UIImage imageNamed:@"wowowow.png"];
    self.photoHead.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/6 - 30);
    [headImageView addSubview:self.photoHead];
    [_photoHead release];
    
    
    //登录后的头像
    self.weiboPhoto  = [[UIImageView alloc]initWithFrame:CGRectMake(110, 60, 80, 80)];
    [headImageView addSubview:self.weiboPhoto];
    self.weiboPhoto.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/6 - 30);
    //self.weiboPhoto.backgroundColor = [UIColor cyanColor];
    //让头像变成圆的
    self.weiboPhoto.clipsToBounds = YES;
    self.weiboPhoto.layer.cornerRadius = 40;
    [_weiboPhoto release];
    
    //微博名字
    self.nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, self.view.frame.size.height * 140 / 667,self.view.frame.size.width * 300 / 375, self.view.frame.size.height * 40 / 667)];
    self.nameLabel.tintColor = [UIColor blackColor];
    self.nameLabel.textAlignment = 1;
    self.nameLabel.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/6 + 40);
    [headImageView addSubview:self.nameLabel];
    [_nameLabel release];
    
    
    
    // 登陆按钮
    self.login = [UIButton buttonWithType:UIButtonTypeSystem];
    self.login.frame = CGRectMake(self.view.frame.size.width * 260 / 375, self.view.frame.size.height * 140 / 667, self.view.frame.size.width * 100 / 375, self.view.frame.size.height * 40 / 667);
    self.login.tintColor = [UIColor blackColor];
    //self.login.backgroundColor = [UIColor yellowColor];
    [self.login setTitle:@"请登录" forState:UIControlStateNormal];
    self.login.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/6 + 25);
    // 给登录按钮一个方法
    [self.login addTarget:self action:@selector(loginClick:) forControlEvents:UIControlEventTouchUpInside];
    // 将登陆按钮添加到header上
    [headImageView addSubview:self.login];
    
    
    
    
    // 设置tableView
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height/8*3, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStyleGrouped];

    tableView.delegate = self;
    tableView.dataSource = self;
    [self.view addSubview:tableView];
    //tableView.rowHeight = 30;
    tableView.backgroundColor = [UIColor clearColor];
    [tableView release];
    

    
//    self.buttonlogin = [UIButton buttonWithType:UIButtonTypeSystem];
//    // self.buttonlogin.frame = CGRectMake([UIScreen mainScreen].bounds.size.width/6*5, 0, [UIScreen mainScreen].bounds.size.width/6, [UIScreen mainScreen].bounds.size.height/16);
//    self.buttonlogin .frame = CGRectMake(20, 0, 40, 40);
//    [self.buttonlogin setTitle:@"分享" forState:UIControlStateNormal];
//    [self.buttonlogin addTarget:self action:@selector(login:) forControlEvents:UIControlEventTouchUpInside];
//    self.buttonlogin.font = [UIFont boldSystemFontOfSize:17];
//    self.navigationItem.leftBarButtonItem =  [[UIBarButtonItem alloc] initWithCustomView:self.buttonlogin];
//    [_buttonlogin release];
//    
//    self.navigationItem.leftBarButtonItem =  [[UIBarButtonItem alloc] initWithCustomView:self.buttonlogin];
////    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"注销" style:1 target:self action:@selector(logoutButton:)] autorelease];
//    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
//    NSLog(@"%@", [user objectForKey:@"userName"]);
//    if ([user objectForKey:@"userName"]) {
//        self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"注销" style:1 target:self action:@selector(logoutButton:)] autorelease];
//    }
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
//    NSLog(@"YONG HU MING : %@", [user objectForKey:@"userName"]);
//    NSLog(@"WEI BO MING : %@", [user objectForKey:@"userHead"]);
    
    if ([user objectForKey:@"userName"]) {
        self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"注销" style:1 target:self action:@selector(zhuxiao:)] autorelease];
        self.login.hidden = YES;
        self.photoHead .hidden = YES;
        self.nameLabel.text = [user objectForKey:@"userName"];
        [self.weiboPhoto setImageWithURL:[NSURL URLWithString:[user objectForKey:@"userHead"]]];
        self.weiboPhoto.hidden = NO;
        self.nameLabel.hidden = NO;
        
    }

}
//微博登陆
- (void)loginClick:(UIButton *)bar
{
    NSLog(@"xcvbnm,");
    WBAuthorizeRequest *request = [WBAuthorizeRequest request];
    request.redirectURI = @"https://www.sina.com";
    request.scope = @"all";
    request.userInfo = @{@"SSO_From": @"LoginViewController",
                         @"Other_Info_1": [NSNumber numberWithInt:123],
                         @"Other_Info_2": @[@"obj1", @"obj2"],
                         @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};     
    [WeiboSDK sendRequest:request];
}


// 通知中心方法


- (void)receiveNotifica:(NSNotification *)center
{
   // NSMutableDictionary *dic = [center.userInfo objectForKey:@"key"];
    // 给我的对象赋值（微博个人信息）
    
    //self.mine = [[Mine alloc] initWithDictionary:dic];
    //    NSLog(@"1111%@", self.mine.screen_name);
    // 一接收到消息通知 立即执行的内容
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"注销" style:UIBarButtonItemStylePlain target:self action:@selector(zhuxiao:)];
    
    self.login.hidden = YES;
    self.photoHead.hidden = YES;
    
    NSString *str = [center.userInfo objectForKey:@"access_token"];
    NSNumber *number = [center.userInfo objectForKey:@"uid"];
    
    //    NSLog(@"%@", str);
    //    NSLog(@"%@", number);
    
    NSString *meshStr = [NSString stringWithFormat:@"https://api.weibo.com/2/users/show.json?uid=%@&access_token=%@", [number description], str];
    NSLog(@"%@",meshStr);
    
    [NetHandler getDataWithUrl:meshStr completion:^(NSData *data) {
        
    
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        //        NSLog(@"%@", resultDic);
        self.weiboObject = [[WeiboLog alloc] initWithDictionary:resultDic];
        
        [_weiboObject release];
        
        self.nameLabel.text = self.weiboObject.screen_name;
        self.nameLabel.hidden = NO;
        // 写一个单例 存储用户登陆信息  用来判断是否登陆
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        [user setObject:self.weiboObject.screen_name forKey:@"userName"];
        [user setObject:self.weiboObject.avatar_hd forKey:@"userHead"];
        NSLog(@"登录时获得的用户头像 url:::%@", self.weiboObject.avatar_hd);
        
        
        //        NSLog(@"%@", self.mine.screen_name);
        self.seeLabel.text = [self.weiboObject.friends_count description];
        self.fansLabel.text = [self.weiboObject.followers_count description];
        self.weiboLabel.text = [self.weiboObject.statuses_count description];
        [self.weiboPhoto setImageWithURL:[NSURL URLWithString:self.weiboObject.avatar_hd]];
        self.weiboPhoto.hidden = NO;
//        NSLog(@"%@=====",self.weiboObject.avatar_hd);
    
    }];
}
//注销
- (void)zhuxiao:(UIBarButtonItem *)noti
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"" message:@"确定注销吗" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
    [alert release];
    alert.tag = 999;
    
    
}
#pragma mark -
#pragma WBHttpRequestDelegate

- (void)request:(WBHttpRequest *)request didFinishLoadingWithResult:(NSString *)result
{
    NSString *title = nil;
    UIAlertView *alert = nil;
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    [user setObject:nil forKey:@"userName"];
    [user setObject:nil forKey:@"userHead"];
    
    //title = NSLocalizedString(@"收到网络回调", nil);
    alert = [[UIAlertView alloc] initWithTitle:title
                                       message:[NSString stringWithFormat:@"注销成功"]
                                      delegate:nil
                             cancelButtonTitle:NSLocalizedString(@"确定", nil)
                             otherButtonTitles:nil];
    [alert show];
    [alert release];
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 888) {
        
        if (buttonIndex == 1) {
            
            NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
            DataBaseHaneler *handler = [DataBaseHaneler shareInstance];
            [handler openDB];
            NSArray *arr = [handler selectAll];
            for (Food *food in arr) {
                
                //当需要删除数据的时候需要对多有存储到数据库中的数据进行遍历 如果数据是当前登录用户存储的 那么就进行删除  如果不是就不能将其删除
                if ([food.currentUserName isEqualToString:[def objectForKey:@"userName"]]) {
                    
                    [handler deleteFoodWithPic_url:food.pic_url];
                    
                }
            
//            [handler deleteFoodWithPic_url:food.pic_url];
            
            }
            self.alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"清除成功" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
            [self.alertView show];
            [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
            
        }

        
        
    }
    
    
    if (alertView.tag == 999) {
        switch (buttonIndex) {
            case 1:
            {
                
                AppDelegate *myDelegate =(AppDelegate*)[[UIApplication sharedApplication] delegate];
                [WeiboSDK logOutWithToken:myDelegate.wbtoken delegate:self withTag:@"user1"];
                
                //延时调用  一秒以后执行
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    self.login.hidden = NO;
                    self.photoHead.hidden = NO;
                    self.navigationItem.rightBarButtonItem = nil;
                    //隐藏的自己的头像
                    self.weiboPhoto.hidden = YES;
                    //隐藏用户的名字
                    self.nameLabel.hidden = YES;
                    
                });
            }
                break;
                
                
            default:
                break;
        }
    }
    
}

// 设置cell的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.array.count;
}

// 设置cell的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *temp = [self.arrayImage objectAtIndex:indexPath.row];
    NSString *str = [self.array objectAtIndex:indexPath.row];
    NSString *string = @"ad";
     MineCellTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
    if (cell == nil) {
        
        cell = [[[MineCellTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string]autorelease];
        
    }
    cell.imageView.image = [UIImage imageNamed:temp];
    cell.textLabel.text = str;
    if (indexPath.row == 0 || indexPath.row == 3 || indexPath.row == 4) {
        
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
    }
    return cell;
}

// 设置cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

// 点击cell的时候执行的方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        
        
        NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
        DataBaseHaneler *handler = [DataBaseHaneler shareInstance];
        // 打开数据库
        [handler openDB];
        // 查询数据
        NSArray *tempArray = [handler selectAll];
        
        if ([def objectForKey:@"userName"] == nil) {
            
            UIAlertView *tempAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [tempAlertView show];
            [tempAlertView release];

            
//            if ([def objectForKey:@"userName"] == nil) {
//                
//                NSLog(@"请先登录");
//                UIAlertView *tempAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
//                [tempAlertView show];
//                [tempAlertView release];
//                
//            } else {
//                
//                UIAlertView *tempAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您还没有收藏!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
//                [tempAlertView show];
//                [tempAlertView release];
            
        } else {
            
            if (tempArray.count == 0) {
                
                UIAlertView *tempAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您还没有收藏!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                [tempAlertView show];
                [tempAlertView release];

            } else {
                
                // 当点击我的收藏的时候推出我的收藏VC
                MyCollectViewController *myCollectVC = [[MyCollectViewController alloc] init];
                [self.navigationController pushViewController:myCollectVC animated:YES];
                [myCollectVC release];
                
            }
        }
        
    } else if (indexPath.row == 1) {
        
        NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
        if ([def objectForKey:@"userName"] == nil) {
            
            UIAlertView *tempAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [tempAlertView show];
            [tempAlertView release];

        } else {
            
            self.alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定清除收藏？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            self.alertView.tag = 888;
            [self.alertView show];
            
        }

    } else if (indexPath.row == 3) {
        
        // 当点击版本信息的时候推出版本信息VC
        VersionInformationViewController *versionInformationVC = [[VersionInformationViewController alloc] init];
        [self.navigationController pushViewController:versionInformationVC animated:YES];
        
        [versionInformationVC release];
    }else if (indexPath.row == 4){
        
        //发送邮件反馈
        if ([MFMailComposeViewController canSendMail]) {
            
            MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
            picker.mailComposeDelegate = self;
            
            [picker setSubject:@"Enter Your Subject!"];
            
            // Set up recipients
            NSArray *toRecipients = [NSArray arrayWithObject:@"15122962900@163.com"];
            
            
            [picker setToRecipients:toRecipients];
            

            // Fill out the email body text
            
            [self presentViewController:picker animated:YES completion:^{
                
            }];
            
        }
        
    } if (indexPath.row == 2) {
        
        float a = [[SDImageCache sharedImageCache] checkTmpSize];
        [[SDImageCache sharedImageCache] clearDisk];
        NSString *str = [NSString stringWithFormat:@"缓存清除成功, 大小为%.2fMB", a];
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:str delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
        [alertView release];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// 定时器方法
- (void)performDismiss:(NSTimer *)timer
{
    [self.alertView dismissWithClickedButtonIndex:0 animated:YES];
    [self.alertView release];
    self.alertView = nil;
}
//发送邮件的方法
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
    
    [self dismissViewControllerAnimated:YES completion:^{
        
        //        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"发送成功！" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        //        [alertView show];
        //        [alertView release];
    }];
}

// 点击提示框走的方法
//- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
//{
//    if (buttonIndex == 1) {
//        
//        DataBaseHaneler *handler = [DataBaseHaneler shareInstance];
//        [handler openDB];
//        NSArray *arr = [handler selectAll];
//        for (Food *food in arr) {
//            
//            [handler deleteFoodWithPic_url:food.pic_url];
//            
//        }
//        self.alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"清除成功" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
//        [self.alertView show];
//        [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
//


//- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
//{
//    if ([alertView isEqual:self.alertView]) {
//        
//        if (buttonIndex == 1) {
//            
//            DataBaseHaneler *handler = [DataBaseHaneler shareInstance];
//            [handler openDB];
//            NSArray *arr = [handler selectAll];
//            for (Food *food in arr) {
//                
//                [handler deleteFoodWithPic_url:food.pic_url];
//                
//            }
//            self.alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"清除成功" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
//            [self.alertView show];
//            [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
//            
//        }
//    }
//}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
